package kz.edu.sdu.itech.pcs.mclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import kz.edu.sdu.itech.pcs.common.Message;
import kz.edu.sdu.itech.pcs.common.MessageType;

import org.apache.log4j.Logger;

public class Monitor implements Runnable {

   static String OK = "OK";
   static Logger log = Logger.getLogger(Monitor.class);

   public static String host = "localhost";
   public static int port = 3333;

   Socket socket;
   Scanner in;
   PrintWriter out;
//      Server server;
   boolean FINISH = false;

   String ip;
   Message message;

   public Monitor() {
   }

   public void connect() {
      try {
         socket = new Socket(host, port);
         in = new Scanner(socket.getInputStream());
         out = new PrintWriter(socket.getOutputStream());
         ip = socket.getInetAddress().getHostAddress();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
      }

   }

   public void close() {
      try {
         in.close();
         out.close();
         socket.close();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
//         server.getWorkerSet().remove(this);
      }

   }

   public void say(MessageType mt) {
      Message m = new Message();
      m.setType(mt);
      say(m);
   }

   public String getSomeName() {
      return ip;
   }

   public void say(Message m) {
      out.println(m.toString());
      out.flush();
      if (AppProps.DEBUG)
         log.debug(String.format("say to %s: %s", getSomeName(), m.toString()));
   }

   public MessageFromServer readResponse() {
      MessageFromServer m = new MessageFromServer(this);
      if (m.read())
         return m;
      return null;
   }

   public synchronized MessageFromServer speak(MessageType mt) {
      Message m = new Message();
      m.setType(mt);
      return speak(m);
   }

   public synchronized MessageFromServer speak(Message m) {
      say(m);
      return readResponse();
   }

   public MessageFromServer request(Message message) {
      connect();
      MessageFromServer r = speak(message);
      close();
      return r;
   }

   @Override
   public void run() {
      request(message);
   }

   public static void sleep(int x) {
      try {
         Thread.sleep(x);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }

   public Message getMessage() {
      return message;
   }

   public void setMessage(Message message) {
      this.message = message;
   }

//      @Override
//      public String toString() {
//         return String.format("ip=%s, name=%s, status=%s, [%.2f]", ip, title, status, getPercentage());

}
